import React, { useState } from 'react';
import { PlusOutlined, RollbackOutlined } from '@ant-design/icons';
import { Button, Form, Popconfirm } from 'antd';
import { formatMessage } from 'umi';
import produce from 'immer';
import Icon from '@/zero/components/Icon';
import SimpleTable from '@/zero/components/Table/Ext/SimpleTable';
import styles from './index.less';

/**
 * 简易 TableForm => 直接编辑
 */
const Index = (props) => {
  const {
    rowKey = 'key',

    columns = [],
    actionColumn = {},

    value = [],
    onChange,

    disabled = false,
    disabledExcludes = [],
    actionsAddonBefore,
    actionsAddonAfter,

    // eslint-disable-next-line
    beforeOk = (newRecord, newValue, actionType, { resolve, reject }) => {
      resolve();
    },

    hideCreate = false, // 隐藏新增按钮 => boolean
    createTemplate = {},
    onCreate,

    hideUpdate = false, // 隐藏修改按钮 => boolean || function
    hideUpdate2Disabled = true,
    onUpdate,

    hideDelete = false, // 隐藏删除按钮 => boolean || function
    hideDelete2Disabled = true,
    onDelete,

    ...rest
  } = props;

  const [form] = Form.useForm();

  const [editingKey, setEditingKey] = useState(null);

  const newValue =
    value?.map((item) => ({
      ...item,
      key: item[rowKey] || item.key || item.id,
    })) || [];

  const newColumns = columns.map((item) => ({
    ...item,
    render: (text, record, index) => {
      const newText = item.render ? item.render(text, record, index) : text;
      if (editingKey && editingKey === record.key) {
        return (
          <div className={styles.editingWrapper}>
            {(typeof item.child === 'function'
              ? item.child({ text, record, index })
              : item.child) || newText}
          </div>
        );
      }
      return newText;
    },
  }));

  const finalColumns = produce(newColumns, (draftState) => {
    if (!disabled || disabledExcludes.length) {
      draftState.push({
        title: formatMessage({ id: '操作' }),
        dataIndex: 'x-action',
        render: (text, record, index) => (
          <>
            {(!disabled || disabledExcludes.includes('actionsAddonBefore')) &&
              (typeof actionsAddonBefore === 'function'
                ? actionsAddonBefore(record, index)
                : actionsAddonBefore)}

            {!disabled &&
              (hideUpdate === false ||
              (typeof hideUpdate === 'function' && !hideUpdate(record, index)) ? (
                <>
                  {!editingKey && (
                    <a
                      onClick={() => {
                        form.setFieldsValue(record);
                        setEditingKey(record.key);
                      }}
                    >
                      <Icon type="icon-xiugai07" />
                    </a>
                  )}
                  {editingKey && editingKey !== record.key && (
                    <a>
                      <Icon type="icon-xiugai07" style={{ color: '#00000040' }} />
                    </a>
                  )}
                  {editingKey && editingKey === record.key && (
                    <>
                      <a
                        onClick={() => {
                          form
                            .validateFields()
                            .then((newRecord) => {
                              const finalRecord = {
                                ...record,
                                ...newRecord,
                              };
                              delete finalRecord.unsaved;
                              new Promise((resolve, reject) => {
                                beforeOk(finalRecord, newValue, 'update', { resolve, reject });
                              }).then(() => {
                                if (onChange) {
                                  onChange(
                                    newValue.map((item) => {
                                      if (item.key === finalRecord.key) {
                                        return finalRecord;
                                      }
                                      return item;
                                    }),
                                  );
                                  if (onUpdate) {
                                    onUpdate(finalRecord, index);
                                  }
                                  setEditingKey(null);
                                }
                              });
                            })
                            .catch((errorInfo) => {
                              if (errorInfo.errorFields) {
                                form.scrollToField(errorInfo.errorFields[0]?.name);
                              } else {
                                console.log(errorInfo);
                              }
                            });
                        }}
                      >
                        <Icon type="icon-baocun" />
                      </a>
                      &nbsp;&nbsp;&nbsp;
                      <a
                        onClick={() => {
                          if (record.unsaved) {
                            onChange(newValue.filter((item) => item.key !== record.key));
                          }
                          setEditingKey(null);
                        }}
                      >
                        <RollbackOutlined />
                      </a>
                    </>
                  )}
                </>
              ) : (
                hideUpdate2Disabled && (
                  <a>
                    <Icon type="icon-xiugai07" style={{ color: '#00000040' }} />
                  </a>
                )
              ))}

            {!disabled &&
              (hideDelete === false ||
              (typeof hideDelete === 'function' && !hideDelete(record, index))
                ? (!editingKey || editingKey !== record.key) && (
                    <>
                      &nbsp;&nbsp;&nbsp;
                      <Popconfirm
                        title={formatMessage({ id: '删除提示' })}
                        onConfirm={() => {
                          new Promise((resolve, reject) => {
                            beforeOk(record, newValue, 'delete', { resolve, reject });
                          }).then(() => {
                            if (onChange) {
                              onChange(newValue.filter((item) => item.key !== record.key));
                              if (onDelete) {
                                onDelete(record, index);
                              }
                            }
                          });
                        }}
                      >
                        <a>
                          <Icon type="icon-shanchu2" />
                        </a>
                      </Popconfirm>
                    </>
                  )
                : hideDelete2Disabled && (
                    <>
                      &nbsp;&nbsp;&nbsp;
                      <a>
                        <Icon type="icon-shanchu2" style={{ color: '#00000040' }} />
                      </a>
                    </>
                  ))}

            {(!disabled || disabledExcludes.includes('actionsAddonAfter')) &&
              (typeof actionsAddonAfter === 'function'
                ? actionsAddonAfter(record, index)
                : actionsAddonAfter)}
          </>
        ),
        ...actionColumn,
      });
    }
    return draftState;
  });

  return (
    <span className={styles.col24}>
      <Form form={form} component={false}>
        <SimpleTable
          pagination={false}
          {...rest}
          rowKey={rowKey}
          columns={finalColumns}
          dataSource={newValue}
          footer={
            !disabled &&
            !hideCreate &&
            !editingKey &&
            (() => (
              <Button
                style={{ width: '100%' }}
                type="dashed"
                icon={<PlusOutlined />}
                onClick={() => {
                  new Promise((resolve, reject) => {
                    beforeOk(createTemplate, newValue, 'create', { resolve, reject });
                  }).then(() => {
                    if (onChange) {
                      const newKey = Date.now();
                      const finalRecord = {
                        key: newKey,
                        [rowKey]: newKey,
                        unsaved: true,
                        ...createTemplate,
                      };
                      onChange(newValue.concat(finalRecord));
                      if (onCreate) {
                        onCreate(finalRecord);
                      }
                      if (Object.keys(createTemplate).length) {
                        form.setFieldsValue(createTemplate);
                      } else {
                        form.resetFields();
                      }
                      setEditingKey(finalRecord.key);
                    }
                  });
                }}
              >
                {formatMessage({ id: '新增' })}
              </Button>
            ))
          }
        />
      </Form>
    </span>
  );
};

Index.displayName = 'SimpleTableForm';
export default Index;
